package com.example.storagemodule

import android.Manifest
import android.app.usage.StorageStatsManager
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.os.storage.StorageManager
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import java.io.*
import java.nio.ByteBuffer

private const val TAG = "FileActivity"

class FileActivity : AppCompatActivity() {
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_f)
	}

	fun save(view: View) {
		//这里有两种模式，一种是MODE_PRIVATE:表示当文件名相同的时候，原有的文件会被覆盖
		//MODE_APPEND:表示当文件名相同的时候，新的内容会追加到原有内容的后面
		//存取和读取目录都是：/data/data/<package_name>/files/
		try {
			val output = openFileOutput("data", Context.MODE_PRIVATE)
			val writer = BufferedWriter(OutputStreamWriter(output))
			writer.use {
				it.write("我好喜欢刘欣悦呀！")
			}
		} catch (e: Exception) {
			e.printStackTrace()
		} finally {

		}
	}

	fun read(view: View) {
		try {
			val content = StringBuilder()
			val input = openFileInput("data")
			val reader = BufferedReader(InputStreamReader(input))
			reader.use {
				reader.forEachLine {
					content.append(it)
				}
			}

			Log.d(TAG, "read: ${content.toString()}")
			Log.d(TAG, "read: ")
		} catch (e: Exception) {
			e.printStackTrace()
		}
	}

	fun save_to_cache(view: View) {
		Log.d(TAG, "save_to_cache: ${this.cacheDir}: ${this.filesDir}")
		Log.d(TAG, "save_to_cache: ${this.getExternalFilesDir(null)?.absolutePath}")
		Log.d(TAG, "save_to_cache: ${this.externalCacheDir?.absolutePath}")
		try {
			val outputFile = FileOutputStream(File(this.cacheDir, "cache_file.txt"))
			val writer = BufferedWriter(OutputStreamWriter(outputFile))
			writer.use {
				it.write("这是测试cache文件的代码！！！11")
			}
		} catch (e: Exception) {
			e.printStackTrace()
		}

	}

	fun read_from_cache(view: View) {}

	@RequiresApi(Build.VERSION_CODES.O)
	fun copy_my3_to_external_file(view: View) {

		if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
			//mp3文件的大小
			val inputFile = assets.open("huranzhijian.mp3")
			val available = inputFile.available()

			val storageService = applicationContext.getSystemService<StorageManager>()!!
			val uuidForPath = storageService.getUuidForPath(filesDir)
			if (storageService.getAllocatableBytes(uuidForPath) > available) {
				Log.d(TAG, "可用的空间为：${storageService.getAllocatableBytes(uuidForPath)}")
//				val byteArray = ByteArray(1024)
				Log.d(TAG, "mp3 size is: $available")
				val file = File(applicationContext.getExternalFilesDir(null), "忽然之间.mp3")
//				var len = -1

				val readBytes = inputFile.readBytes()
				val outputFile = FileOutputStream(file)
				outputFile.write(readBytes)
				outputFile.close()
				inputFile.close()
			}

		}
	}

	fun read_all_picture(view: View) {
		requestMyPermission()
	}

	private fun requestMyPermission() {
//		TODO("Not yet implemented")
		if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
			ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),1)
		}
	}

	@RequiresApi(Build.VERSION_CODES.R)
	override fun onRequestPermissionsResult(
		requestCode: Int,
		permissions: Array<out String>,
		grantResults: IntArray
	) {
//		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
		when(requestCode){
			1->{
				if(grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
					readPictrue()
				}
				else{
					Log.d(TAG, "你没有授予读内存卡的权限！")
				}
			}

			2->{
				if(grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
					ss()
				}
				else{
					Log.d(TAG, "你没有授予读内存卡的权限！")
				}
			}
		}
	}

	@RequiresApi(Build.VERSION_CODES.R)
	private fun readPictrue(){
		Log.d(TAG, "获取所有视频：")
		val query = contentResolver.query(
			MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(
				MediaStore.Images.Media._ID,
	MediaStore.Images.Media.MIME_TYPE,
				MediaStore.Images.Media.TITLE
			),
			null, null, null
		)
		query?.use { cursor ->

			// Cache column indices.
			val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
			val mimeC = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE)
			val titleC = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE)
			while (cursor.moveToNext()) {
				// Get values of columns for a given video.
				val id = cursor.getLong(idColumn)
				val mime=cursor.getString(mimeC)
				val title = cursor.getString(titleC)

				val contentUri: Uri = ContentUris.withAppendedId(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					id
				)

				// Stores column values and the contentUri in a local object
				// that represents the media file.
//				videoList += Video(contentUri, name, duration, size)
				Log.d(TAG, "${contentUri},${mime},$title")
			}
		}
	}

	fun store_all(view: View) {
		if(Environment.getExternalStorageState()==Environment.MEDIA_MOUNTED){
			Log.d(TAG, "外部存储空间的根目录是：${this.getExternalFilesDir(null)}")
			Log.d(TAG, "外部存储空间的根目录是：${Environment.getExternalStorageDirectory()}")
			Log.d(TAG, "外部存储空间的根目录是：${getExternalFilesDir(Environment.DIRECTORY_DCIM)}")

			if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
				ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),2)
			}


		}
	}

	fun ss(){
		val file = File(Environment.getExternalStorageDirectory(), "11111.text")
		if(file.exists()){
			Log.d(TAG, "成功")
		}else
			Log.d(TAG, "失败")

		val fileWriter = FileWriter(file)
		fileWriter.write("这是测试File API的内容")
		fileWriter.close()
	}

	fun system_pick(view: View) {
		openFile()
		StatFs("")
	}

	// Request code for selecting a PDF document.
	 val PICK_PDF_FILE = 2

	fun openFile() {
		val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
			addCategory(Intent.CATEGORY_OPENABLE)
			type = "*/*"

			// Optionally, specify a URI for the file that should appear in the
			// system file picker when it loads.

		}

		startActivityForResult(intent, PICK_PDF_FILE)
	}
}
